#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer{
public:
    Computer(const char * brand,double price)
        : _brand(new char[strlen(brand) + 1]())
          , _price(price)
    {
        strcpy(_brand,brand);
        cout << "Computer(const char *,double)" << endl;
    }

    Computer(const Computer & rhs)
        : _brand(new char[strlen(rhs._brand) + 1]())
          , _price(rhs._price)
    {
        strcpy(_brand,rhs._brand);
        /* rhs._price = 100; */
        cout << "Computer(const Computer &)" << endl;
    }

    Computer & operator=(const Computer & rhs){
        if(this != &rhs){//1.考虑自复制问题
            delete [] _brand;//2.回收左操作数原本申请的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝(复制)
            strcpy(_brand,rhs._brand);
            _price = rhs._price;
            cout << "Computer & operator=" << endl;

        }
        return *this;//4.返回*this
    }

    void print(){
        cout << "brand:" << _brand << endl
            << "price:" << _price << endl;
    }

    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
        cout << "~Computer()" << endl;
    }
private:
    char * _brand;
    double _price;
};

#if 0
//引用作为函数参数的意义：避免复制
void func1(Computer & pc){
    pc.print();
}

void test0(){
    Computer pc1("Apple",12000);
    func1(pc1);
}
#endif

#if 1
//引用作为返回类型也是避免复制
Computer & func2(){
    Computer pc("HuaWei",7600);
    return pc;
}

void test1(){
    /* func2(); */
    /* func2().print(); */
    /* cout << endl; */
    /* Computer("XiaoMi",4500).print(); */
    cout << &func2() << endl;
}
#endif


int main(void){
    /* test0(); */
    test1();
    return 0;
}
